// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

// 获取数据库引用
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const { process, openid } = event; // 获取传入的 process 和 openid

  try {
    // 检查传入的参数是否有效
    if (!process || !openid) {
      return {
        data: {
          status: 404,
          message: '数据不完整'
        },
      };
    }

    let queryConditions = {};

    // 根据 process 的值构造查询条件
    switch (process) {
      case 0:
        queryConditions = {
          openid: openid,
          process: 0
        };
        break;
      case 1:
        queryConditions = {
          openid: openid,
          process: 1
        };
        break;
      case 2:
        queryConditions = {
          $or: [
            { openid: openid, process: 0 },
            { openid: openid, process: 1 }
          ]
        };
        break;
      default:
        return {
          error: 'Invalid process value.'
        };
    }

    // 查询数据库，并按 createTime 降序排序
    const result = await db.collection('order')
      .where(queryConditions)
      .orderBy('createTime', 'desc') // 按 createTime 降序排序
      .field({
        createTime: true,
        openid:true,
        process:true,
        totalValue:true,
        _id:true
      })
      .get();
      

    // 返回查询结果
    return {
      data: {
        data:result.data,
        status: 200,
        message: '获取成功'
      },
    };
  } catch (err) {
    console.error(err);
    throw err;
  }
};